<template>
  <div id="fullsemi-page" style="text-align: left">
    <a-layout id="layout-sider" :style="{height:'100vh'}">
      <a-layout-sider
          v-if="device != 'mobile' && showLayout"
          collapsedWidth="0"
          v-model="collapsed"
          width="240px"
          :style="theme"
      >
        <div>
          <div @dblclick="showLink = !showLink">
            <logo></logo>
          </div>

          <a-input v-show="showLink" v-model="wantPath" @pressEnter="jumpPath" placeholder="快速跳转"></a-input>
          <a-menu :theme="navigationTheme" mode="inline" :open-keys="openKeys"
                  :default-selected-keys="['notice']" @openChange="onOpenChange" @click="clickMenuItem"
                  v-model="menuKeys">
            <template v-for="item in menuMain">
              <a-menu-item :key="item.key" v-if="item.isMenuItem">
                <router-link :target="gotoType" :to="item.path">
                  <a-icon :type="item.icon"/>
                  <span>{{ $t(item.title) }}</span>
                </router-link>
              </a-menu-item>
              <template v-else>
                <a-sub-menu :key="item.key" style="text-align: left">
                                   <span slot="title">
                                                    <a-icon :type="item.icon" :theme="item.theme"/>
<!--                                                    <span>{{ item.key + ':' + $t(item.title) }}</span>-->
                                                    <span>{{ $t(item.title) }}</span>
                                                </span>
                  <template v-for="r in item.menu">
                    <template v-if="r.hasItem">
                      <a-sub-menu :key="r.name">
                                                    <span slot="title">
                                                    <a-icon :type="item.icon" :theme="item.theme"/>
                                                    <span v-if="r.name.indexOf('report')===0">{{ $t(r.label) }}</span>
<!--                                                    <span v-else>{{ r.name + ':' + $t(r.label) }}</span>-->
                                                      <span v-else>{{ $t(r.label) }}</span>
                                                </span>
                        <template v-for="e in r.childMenu">
                          <a-menu-item :key="e.name" @click="changeViewKey(e.name)">
                            <router-link :target="gotoType" :to="e.path">
                              <a-icon :type="item.icon"/>
                              <span v-if="e.name.indexOf('report')===0">{{ $t(e.label) }}</span>
<!--                              <span v-else>{{ e.name + ':' + $t(e.label) }}</span>-->
                              <span v-else>{{  $t(e.label) }}</span>
                            </router-link>
                          </a-menu-item>
                        </template>
                      </a-sub-menu>
                    </template>
                    <a-menu-item v-else-if="r.isSystem" :key="r.name"
                                 @click="jumpOtherSys(r.url)">
                      <a-icon :type="item.icon"/>
                      <span>{{$t(r.label) }}</span>
                    </a-menu-item>
                    <a-menu-item v-else :key="r.name">
                      <router-link :target="gotoType" :to="r.path">
                        <a-icon :type="item.icon"/>
                        <!--                                                报表（路由name以report开头）不展示前部的路由name-->
                        <span v-if="r.name.indexOf('report')===0">{{ r.label }}</span>
<!--                        <span v-else>{{ r.name + ':' + $t(r.label) }}</span>-->
                        <span v-else>{{  $t(r.label) }}</span>
                      </router-link>
                    </a-menu-item>
                  </template>
                </a-sub-menu>
              </template>
            </template>

          </a-menu>
        </div>
      </a-layout-sider>
      <a-layout>
        <a-layout-header class="fullsemi-header"
                         :style="{ background: '#fff', padding: 0,height:'5vh', lineHeight:'4vh'}"
                         v-if="showLayout"
        >
          <a-row>
            <a-col :xs="1" :span="1" :sm="1" align="middle" style="line-height: 40px">
              <a-icon class="trigger"
                      :type="collapsed ? 'menu-unfold' : 'menu-fold'"
                      @click="()=> collapsed = !collapsed"
              />
            </a-col>
            <a-col :xs="14" :span="14" :sm="14" :style="{lineHeight:'44px'}">
              <a-col :span="12">
              </a-col>
              <a-col :span="12">
                <span align="middle">{{ $t('menu.titleName') }}</span>
              </a-col>
            </a-col>
            <a-col :xs="9" :span="9" :sm="9">
              <a-row justify="end" type="flex">
                <a-col>
                  <div style="width: 300px">
                    <a-menu class="layoutTop" mode="horizontal"  style="height: 5vh;border: none">
                      <a-sub-menu>
                        <div slot="title">
                          <a-icon type="user"></a-icon><span style="font-size: large; font-weight: bold">{{ usrName }}</span>
                        </div>
                        <a-menu-item key="setting:2">
                          <router-link @click.native="logoutClick" to="/logout">
                            <span>{{ $t('logout') }}</span>
                          </router-link>
                        </a-menu-item>
<!--                        <a-menu-item @click="visible=true" key="setting:1">-->
<!--                          {{ $t('changePassword') }}-->
<!--                        </a-menu-item>-->
                      </a-sub-menu>

                      <a-menu-item>
                        <span>{{this.userId}}</span>
                      </a-menu-item>


                      <a-menu-item @click="changeGotoType" key="changeGotoType">
                        <a-tooltip placement="left" title="Jump Method">
                          <icon-goto></icon-goto><span style="font-size: large; font-weight: bold">{{getGotoName(gotoType)}}</span>
                        </a-tooltip>
                      </a-menu-item>

<!--                      <a-menu-item key="upgradeLog">-->
<!--                        <a-tooltip placement="left" title="更新日志">-->
<!--                          <router-link target="" to="/ChangeLog">-->
<!--                            <icon-upgrade></icon-upgrade><span style="font-size: large; font-weight: bold">更新日志</span>-->
<!--                          </router-link>-->
<!--                        </a-tooltip>-->
<!--                      </a-menu-item>-->

                      <a-menu-item @click="changeTheme" key="changeTheme">
                        <a-tooltip placement="left" title="Switch Theme">
                          <icon-change-theme></icon-change-theme><span style="font-size: large; font-weight: bold">Switch Theme</span>
                        </a-tooltip>
                      </a-menu-item>
                      <a-sub-menu>
                                                <span slot="title" style="font-size: large; font-weight: bold">
                                                <icon-language></icon-language>
                                                {{ $t('language') }}</span>
                        <a-menu-item key="locale:1" @click="setLocal('zh')"><span style="font-size: large; font-weight: bold">{{ $t('zh') }}</span></a-menu-item>
                        <a-menu-item key="locale:2" @click="setLocal('en')"><span style="font-size: large; font-weight: bold">{{ $t('en') }}</span></a-menu-item>
                      </a-sub-menu>
                    </a-menu>
                  </div>
                </a-col>
              </a-row>
            </a-col>
          </a-row>
        </a-layout-header>
        <a-layout-content class="fullsemi-content">
          <router-view :key="viewKey"/>
        </a-layout-content>
        <setting-drawer ref="settingDrawer"></setting-drawer>
      </a-layout>
    </a-layout>

    <!--修改密码-->
<!--    <a-modal title="修改密码" v-model="visible" @ok="updatePassword" @cancel="visible=false"-->
<!--             :okText="$t('btn.confirm')" :cancelText="$t('btn.cancel')">-->
<!--      <a-form-model ref="changePasswordRef"-->
<!--                    :model="passwordForm"-->
<!--                    :rules="rules"-->
<!--                    layout="inline" :label-col="{span:8}" :wrapper-col="{span:14}">-->
<!--        <a-form-model-item label="旧密码" prop="oldPassword">-->
<!--          <a-input-password v-model="passwordForm.oldPassword"></a-input-password>-->
<!--        </a-form-model-item>-->
<!--        <a-form-model-item label="新密码" prop="newPassword">-->
<!--          <a-input-password v-model="passwordForm.newPassword"></a-input-password>-->
<!--        </a-form-model-item>-->
<!--        <a-form-model-item label="新密码确认" prop="confirmPassword">-->
<!--          <a-input-password v-model="passwordForm.confirmPassword"></a-input-password>-->
<!--        </a-form-model-item>-->
<!--      </a-form-model>-->
<!--    </a-modal>-->

    <error-code></error-code>

    <a-modal
        :visible="gotoModalVisible"
        @cancel="closeGotoModal"
        @ok="gotoModalOk"
        title="Select Jump Method"
    >
      <a-form-model :labelCol="{span: 7}" :model="gotoForm" :rules="gotoFormRules" :wrapperCol="{span: 13}" layout="inline" ref="gotoForm">
        <a-form-model-item label="Jump Method" prop="gotoType">
          <a-select allowClear optionFilterProp="children" showSearch v-model="gotoForm.gotoType">
            <a-select-option :key="d.value" :title="d.label" :value="d.value" v-for="d in gotoData">{{d.label}}</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

  </div>
</template>
<script>
import {mapState, mapMutations} from 'vuex';
import {mixinDevice} from '@/util/mixin';
import Logo from '@/components/Logo'
import SendMsg from "@/api/SendMsg";
import SettingDrawer from '@/components/settingDrawer/SettingDrawer'
import ACol from "ant-design-vue/es/grid/Col";
import {v4 as uuidv4} from 'uuid';

import authorityData from "../util/authorityData";

import {resetRouter} from "../router";
import ErrorCode from "../components/ErrorCode";
import IconChangeTheme from "@/components/icon/IconChangeTheme";
import IconLanguage from "@/components/icon/IconLanguage";
import IconGoto from "../components/icon/IconGoto";
import LoginService from "../api/LoginService";

export default {
  mixins: [mixinDevice],
  components: { IconGoto, IconChangeTheme, ErrorCode, ACol, Logo, SettingDrawer,IconLanguage},//IconUpgrade IconLanguage IconFab
  computed: {
    ...mapState(["device", "navigationTheme", "openKeys", 'currentLocale','firstLoginFlag',]),
    theme: function () {
      if (this.navigationTheme == 'dark') {
        return {height: '100vh', overflow: 'auto', left: 0, backgroundColor: 'black',};
      }
      return {height: '100vh', overflow: 'auto', left: 0, backgroundColor: 'white',};
    },
    gotoType() {
      if (this.gotoForm.gotoType === '_blank') {
        return '_blank';
      } else {
        return '_self';
      }
    },
    menuKeys: {
      get: function () {
        return this.$store.state.menuKeys
      },
      set: function (val) {
        // 点击子菜单的时候，将展开的节点和选中的节点存起来
        console.info(this.$store.state.openKeys)
        window.localStorage.setItem('openKeys', JSON.stringify(this.$store.state.openKeys))
        window.localStorage.setItem('menuKeys', JSON.stringify(val))
        // 2021-04-19: 取消单击时选中菜单项，容易造成误解
        // this.setMenuKeys(val)
      }
    },
    showLayout() {
      let notShowList = ['Help', 'ChangeLog']
      return notShowList.indexOf(this.$route.name) === -1
    },
    rootSubmenuKeys(){
      return authorityData.map( e => e.key)
    }
  },
  data() {
    let validatePass = (rule, value, callback) => {
      if (value !== '') {
        if (this.passwordForm.confirmPassword !== '') {
          this.$refs.changePasswordRef.validateField('confirmPassword');
        }
        callback();
      }
      callback();
    };
    let validatePass2 = (rule, value, callback) => {
      if (value !== '' && value !== this.passwordForm.newPassword) {
        callback(new Error("两次密码不一样!"));
      } else {
        callback();
      }

    };
    return {
      usrName: '',
      rules: {
        newPassword: [{required: true, message: '请输入新密码', trigger: ['blur']},
          {validator: validatePass, trigger: ['change', 'blur']}],
        confirmPassword: [{required: true, message: '请确认密码', trigger: ['blur']},
          {validator: validatePass2, trigger: ['change', 'blur']}],
        oldPassword: [{required: true, message: '请输入旧密码', trigger: ['change', 'blur']}],
      },
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      collapsed: false,
      userId: window.localStorage.getItem('userIdMes'),
      visible: false,
      formItemLayout: {
        labelCol: {span: 10},
        wrapperCol: {span: 12}
      },
      form: this.$form.createForm(this),
      password: "",
      agentVisible: false,
      agentForm: {
        agentUserId: '',
        startTime: '',
        endTime: ''
      },
      startValue: null,
      endValue: null,
      agentRules: {
        agentUserId: [{required: true, message: '请输入代理人工号', trigger: ['blur']}],
        startTime: [{required: true, message: '请确认开始时间', trigger: ['change','blur']}],
        endTime: [{required: true, message: '请输入结束时间', trigger: [ 'change','blur']}],
      },
      agentUserList:JSON.parse(window.localStorage.getItem("allUserInfo")),
      // rootSubmenuKeys: ['公告', 'basic', '1000', '2000', '3000', '4000', '5000', '6000', '7000', '8000', '9000', 'A000', 'Report', 'Demo'],
      menuMain: [],
      showLink: false,
      wantPath: '',
      gotoData: [
        {
          label: 'current window',
          value: '_self'
        },
        {
          label: 'new window',
          value: '_blank'
        },
      ],
      gotoForm: {
        gotoType: window.localStorage.getItem('gotoType'),
      },
      gotoModalVisible: false,
      gotoFormRules: {
        gotoType: [{required: true, message: 'Please select a jump method', trigger: 'change'}]
      },
      viewKey: uuidv4(),
      buttonCodeList:[],
      permissionTree:[],
      addRouters: [],
    };
  },

  watch: {
    device: function () {
       this.collapsed = !!this.isMobile();
    },
    //改变国际化时，重新获取菜单
    currentLocale() {
      this.initMainMenu()
    },
    startValue(val) {
      console.log('startValue', val);
    },
    endValue(val) {
      console.log('endValue', val);
    },
  },
  mounted() {
    this.queryRoute()
  },
  methods: {
    ...mapMutations(['setMenuKeys','setInitLoginFlag','setUserButtons']),
    updatePassword() {
      this.$refs.changePasswordRef.validate(valid => {
        if (valid) {
          let codeInTrx = {
            trxId: "sysUser",
            actionFlg: "G",
            oldPassword:this.passwordForm.oldPassword,
            newPassword: this.passwordForm.newPassword,
          };
          SendMsg.sendPostTrx(codeInTrx).then((res) => {
            let outTrx = res.data;
            if (outTrx.rtnCode === '0000000') {
              this.$message.success('密码修改成功');
              this.logoutClick();
              this.visible = false;
              this.$router.push({path: '/'})
            }
          });
        }
      });

    },

    changeViewKey(name) {
      if (name.indexOf('report')===0) {
        this.$nextTick(() => {
          this.viewKey = uuidv4();
        });
      }
    },
    getGotoName(val) {
      let index = this.gotoData.findIndex(e => e.value === val);
      if (index !== -1) {
        return this.gotoData[index].label;
      }
      return val;
    },
    changeGotoType(){
      this.gotoModalVisible = true;
      this.gotoForm.gotoType = this.gotoType  || '';
    },
    gotoModalOk(){
      this.$refs.gotoForm.validate( valid => {
        if(valid){
          window.localStorage.setItem('gotoType', this.gotoForm.gotoType)
          this.gotoModalVisible = false
        }
      })
    },
    closeGotoModal(){
      let gotoType = window.localStorage.getItem('gotoType')
      if(!gotoType){
        this.$message.warn('请选择跳转方式并点击确认')
      }else{
        this.gotoModalVisible = false
      }
    },
    changeTheme(){
      this.$refs.settingDrawer.toggle()
    },
    //查询路由
    queryRoute(state){
      let codeInTrx = {
        trxId: "sysPermission",
        actionFlg: "QB",
        permissionType:"button",
      };
      SendMsg.sendPostTrx(codeInTrx).then((res) => {
        let outTrx = res.data;
        console.log(outTrx,'路由数据')
        if ('0000000' === outTrx.rtnCode) {
          this.buttonCodeList = outTrx.buttonCodeList
          this.permissionTree = outTrx.permissionTree

          this.setUserButtons(outTrx.buttonCodeList)
          this.initMainMenu()
        }
      }).finally(() => {
      });
    },
    extractTree(data){
      data.forEach(item => {
        this.addRouters.push({...item})
        if(item.child?.length){
          this.addRouters = this.extractTree(item.child);
        }
      });
      return this.addRouters;
    },

    getMainData(list) {
      return list.map(ele => {
        let item = {
          key: ele.key,
          title: ele.title,
          icon: ele.icon
        }
        if (ele.isMenuItem) {
          item.isMenuItem = true;
          item.path = ele.path;
          item.route = {
            path: ele.path,
            name: ele.name,
            component: ele.component,
            meta: ele.meta,
          };
        } else {
          item.menu = ele.children ? ele.children.filter(sub => {
            if (sub.meta) {
              return !sub.meta.hide
            }
            return true

          }).map(sub => {
            if (sub.menu) {
              let childMenu = sub.children.map(child => {
                return {
                  name: child.name,
                  path: child.path,
                  isSystem: child.isSystem,
                  auth: child.meta.auth,
                  label: child.meta.title,
                  url: child.meta.url,
                  route: {
                    path: child.path,
                    name: child.name,
                    component: child.component,
                    meta: child.meta
                  },
                }
              })

              return {
                name: sub.name,
                path: sub.path,
                isSystem: sub.isSystem,
                label: sub.title,
                url: sub.url,
                hasItem: true,
                childMenu: childMenu
              }
            }
            return {
              name: sub.name,
              path: sub.path,
              isSystem: sub.isSystem,
              auth: sub.meta.auth,
              label: sub.meta.title,
              url: sub.meta.url,
              route: {
                path: sub.path,
                name: sub.name,
                component: sub.component,
                meta: sub.meta
              },
            }
          }) : null
        }
        return item
      })
    },
    // 过滤树节点
    assemble(tree) {
      var newArr = [];
      for (var i = 0; i < tree.length; i++){
        var item = tree[i];
        if(item.name === 'T001') {
          tree.splice(i--, 1);
        } else {
          if (item.childNodes) {
            item.childNodes = this.assemble(item.childNodes);
          }
          newArr.push(item);
        }
      }
      return newArr;
    },
    initMainMenu() {
      const addRouters = this.extractTree(this.permissionTree).map(item => item.permissionCode);

      // const list = authorityData.filter(item => addRouters.includes((item.name)));
      // console.log(authorityData,'authorityData')
      // console.log(list,'list')

      const filterMenu = (menuList, menuCode) => {
        return menuList.filter(item => {
          return menuCode.indexOf(item.name) > -1
        }).map(item => {
          item = Object.assign({}, item)
          if (item.children) {
            item.children = filterMenu(item.children, menuCode)
          }
          return item
        })
      }
      const myMenu = filterMenu(authorityData, addRouters)

      // let listFilter = authorityData.filter(item => {
      //   if (item.children) {
      //     console.log(item,'111')
      //     item.children = item.children.filter(el => addRouters.includes((el.name)))
      //   } else {
      //     addRouters.includes((item.name))
      //   }
      // });
      // console.log(listFilter,'listFilter')


      // 所有路由信息
      let main = this.getMainData(myMenu);
      //根据权限生成路由
      let routes = []
      main.forEach(item => {
        if (item.isMenuItem) {
          routes.push({ ...item.route });
        } else {
          let route = item.menu.filter(e => !e.hasItem).map(e => {
            return {
              ...e.route,
            }
          })

          if (route.length !== 0) {
            routes.push(...route)
          }

          item.menu.filter(e => e.hasItem).map(se => {
            let items = se.childMenu.map(e => {
              return {
                ...e.route,
              }
            })
            routes.push(...items)
          })
        }

      })
      let errorPage = {
        path: "*",
        redirect: '/404'
      }
      let routeList = []

      if(this.buttonCodeList[0].parentId == '-1') {
        let routeTop = {
          path: '/notice',
          name: 'notice',
          component: () => import("../views/Notice/Notice.vue"),
        }
        if(this.buttonCodeList[0].hasChildren){
          routeList = this.buttonCodeList[0].child.map(el => {
            let obj = {
              path: '/'+ el.permissionCode,
              name: el.permissionCode,
              component: () => import("../views/Notice/Notice.vue"),
            }
          })
        }
      }
      this.menuMain = main;
      //先重置路由
      this.$router.matcher = resetRouter().matcher
      this.$router.addRoutes([...routes, errorPage ])

      // let lastRoute = window.localStorage.getItem('lastRoute')
      // if (this.firstLoginFlag && lastRoute){
      //   this.$router.push({path: lastRoute});//跳转到上次跳转页面
      // }
      // this.setInitLoginFlag(false)
    },
    jumpPath() {
      this.$router.push(this.wantPath).catch(e => {
      })

      this.wantPath = ''
    },
    jumpOtherSys(url) {
      window.open(url )
    },
    setLocal(val) {
      location.reload();
      window.localStorage.setItem('locale', val)
      this.$i18n.locale = val;
      this.$store.state.currentLocale = val
    },
    logoutClick() {
      LoginService.logout().then( () => {
        localStorage.removeItem('access_token');
        localStorage.removeItem('userIdMes');
        localStorage.removeItem('permissionList');
        this.$router.push({path: '/login'})
      })
    },
    onOpenChange(openKeys) {
      let result = []
      const latestOpenKey = openKeys.find(key => this.$store.state.openKeys.indexOf(key) === -1);
      if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
        result = openKeys;
      } else {
        result = latestOpenKey ? [latestOpenKey] : [];
      }
      let hasMainMenuKey = result.some(r => this.rootSubmenuKeys.findIndex(k => k === r) !== -1)
      this.$store.state.openKeys = hasMainMenuKey ? result : []
    },
    clickMenuItem({key, keyPath}) {
      window.localStorage.setItem('menuPath', JSON.stringify(keyPath))
      if (key === 'notice') {
        this.$store.state.openKeys = []
      }
    },
  },

};
</script>
<style lang="less" >
@import "../styles/theme/variables.less";

.layoutTop .ant-menu-submenu-title {
  font-weight: bold;
  font-size: large;
}

#layout-sider .trigger {
  margin: 4px;
  font-size: 18px;
  line-height: 40px;
  cursor: pointer;
  transition: color .3s;
}

#layout-sider .trigger:hover {
  color: #1890ff;
}

#layout-sider .logo {
  height: 15vh;
  background: rgba(255, 255, 255, .1);
  margin: 0px 0px 0px 0px;
}

.ant-form-item {
  width: 100%;
}

</style>


